//
//  DoImagePickerManager.m
//  cloudstudy-revive-applestore
//
//  Created by jieer on 2019/1/2.
//  Copyright © 2019年 sdgh. All rights reserved.
//

#import "DoImagePickerManager.h"


@implementation DoImagePickerManager

+ (DoImagePickerManager*) instance
{
    static DoImagePickerManager *instance = nil;
    
    @synchronized (self) {
        if (!instance)
            instance = [[DoImagePickerManager alloc] init];
    }
    
    return instance;
}
#pragma mark 获得所有的相册数组
-(NSMutableArray<PHAssetCollection*>*)getAllAssetCollections
{
    
    // 获得所有的自定义相簿
    PHFetchResult<PHAssetCollection *> *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    
    // 获得相机胶卷
    PHAssetCollection *cameraRoll = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil].lastObject;
    
    NSMutableArray* photoCollections = [NSMutableArray new];
    for (PHAssetCollection *assetCollection in assetCollections) {
        [photoCollections addObject:assetCollection];
    }
    [photoCollections addObject:cameraRoll];
    return photoCollections;
}




#pragma mark 获得某相册的对象
-(Photo*)getPhoto:(NSString*)title
{
    Photo* photo = [[Photo alloc]init];
    __block NSMutableArray* photoList = [self getAllAssetCollections];
    for (PHAssetCollection* assetAlbum in photoList) {
        if ([assetAlbum.localizedTitle isEqualToString:title]) {
            photo.title = assetAlbum.localizedTitle;
            
            PHFetchOptions *fetchOptions = [PHFetchOptions new];
            fetchOptions.sortDescriptors = @[
                                             [NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO],
                                             ];
            
            PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsInAssetCollection:assetAlbum options:fetchOptions];
            photo.photoNum = assets.count;
            NSMutableArray<PHAsset*> *assetsList = [NSMutableArray new];
            [assets enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                PHAsset *asset = (PHAsset *)obj;
                //                NSLog(@"照片名%@", [asset valueForKey:@"filename"]);
                [assetsList addObject:asset];
            }];
            if (assetsList.count>0) {
                photo.coverImg = [DoImagePickerManager getImgFromAsset:assetsList[0]];
                
            }
            
            photo.assetList = assetsList;
            
            
        }
    }
    
    
    return photo;
}


#pragma mark - 获取相册内所有照片(虚拟相册)的对象
- (Photo *)getAllAsset:(BOOL)selImage
{
    NSMutableArray<PHAsset *> *assets = [NSMutableArray array];
    
    PHFetchOptions *option = [[PHFetchOptions alloc] init];
    //ascending 为YES时，按照照片的创建时间升序排列;为NO时，则降序排列
    option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
    
//    PHAssetMediaTypeImage
//    PHAssetMediaTypeVideo
    
//    PHFetchResult tme = [PHAssetCollection fetchAssetCollectionsWithType:<#(PHAssetCollectionType)#> subtype:<#(PHAssetCollectionSubtype)#> options:<#(nullable PHFetchOptions *)#>]
    
    PHFetchResult *result = nil;
    if (selImage)
    {
        result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:option];
    }
    else
    {
        result = [PHAsset fetchAssetsWithOptions:option];
    }
//    PHFetchResult *result = [PHAsset fetchAssetsWithOptions:option];//[PHAsset fetchAssetsWithMediaType:(PHAssetMediaTypeImage | PHAssetMediaTypeVideo) options:option];
    
    [result enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        PHAsset *asset = (PHAsset *)obj;
        if (asset.mediaType == PHAssetMediaTypeVideo)
        {
//            NSLog(@"视频");
            [assets addObject:asset];
        }
        else if (asset.mediaType == PHAssetMediaTypeAudio)
        {
//            NSLog(@"音频");
        }
        else if (asset.mediaType == PHAssetMediaTypeImage)
        {
            [assets addObject:asset];
        }
//        NSLog(@"照片名%@", [asset valueForKey:@"filename"]);
        
    }];
    Photo* photo = [[Photo alloc]init];
    
    if (assets.count > 0)
    {
        PHAsset* asset = assets[0];
        photo.coverImg = [DoImagePickerManager getImgFromAsset:asset];
        
    }else
    {
        photo.coverImg = [UIImage imageNamed:@""];
    }
    
    photo.photoNum = assets.count;
    photo.title = @"所有照片";
    photo.assetList = assets;
    return photo;
}

#pragma mark - 获得原图
+(void)getOriginalImage:(PHAsset*)asset block:(void(^)(UIImage*image))block
{
    __block UIImage* image = [self getImgFromAsset:asset];
    
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    // 同步获得图片, 只会返回1张图片
    options.synchronous = YES;
    CGSize size = CGSizeMake(asset.pixelWidth, asset.pixelHeight);
    [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        NSString* fileStr = [info objectForKey:@"PHImageFileSandboxExtensionTokenKey"];
        if (fileStr.length > 0) {
            block(result);
        }else
        {
            block(image);
        }
    }];
    
    
    
}


#pragma mark - 获得缩略图
+(UIImage*)getImgFromAsset:(PHAsset*)asset
{
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    // 同步获得图片, 只会返回1张图片
    options.synchronous = YES;
    options.resizeMode = PHImageRequestOptionsResizeModeExact;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    __block UIImage* image;
    [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:CGSizeMake(300, 300) contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        NSLog(@"info1===%@     %@",info,result);
        
        image = result;
    }];
    return image;
}

#pragma mark - 重新刷新cell上面的数字
+(void)reloadLabel:(NSMutableArray<NSNumber *>*)btnArray  collection:(UICollectionView*)collection;
{
    if (btnArray.count == 0)
    {
        return;
    }
    for (int i = 0; i < btnArray.count; i++)
    {
        NSInteger x = [btnArray[i] integerValue];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:x inSection:0];
        DoImagePickerCollectionViewCell*cell=(DoImagePickerCollectionViewCell*)[collection cellForItemAtIndexPath:indexPath];
        cell.selectBtn.hidden = NO;
        cell.selectBtn.selected = YES;
        [cell.selectBtn setTitle:[NSString stringWithFormat:@"%d",i+1] forState:UIControlStateSelected];
    }
}



+(UIImage*)getImg:(PHAsset*)asset
{
    __block UIImage* image;
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    // 同步获得图片, 只会返回1张图片
    options.synchronous = YES;
    CGSize size = CGSizeMake(asset.pixelWidth, asset.pixelHeight);
    [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        image = result;
    }];
    return image;
}


+(void)downlodImageForAssets:(PHAsset*)asset getImage:(void(^)(UIImage*image))success
{
    __block UIImage*image;
    
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_async(queue, ^{
        CGSize imageSize = CGSizeMake(asset.pixelWidth, asset.pixelHeight);
        PHImageRequestOptions*options = [[PHImageRequestOptions alloc]init];
        options.resizeMode = PHImageRequestOptionsResizeModeExact;
        options.networkAccessAllowed = NO;
        options.synchronous = YES;
        
        [[PHCachingImageManager defaultManager]requestImageForAsset:asset targetSize:imageSize contentMode:PHImageContentModeAspectFill options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info)
         {
             if (result) {
                 image = result;
             }
         }];
        
        if (image == nil) {
            CGSize imageSize = CGSizeMake(asset.pixelWidth, asset.pixelHeight);
            PHImageRequestOptions*options = [[PHImageRequestOptions alloc]init];
            options.resizeMode = PHImageRequestOptionsResizeModeExact;
            options.networkAccessAllowed = YES;
            options.synchronous = YES;
            
            [[PHCachingImageManager defaultManager]requestImageForAsset:asset targetSize:imageSize contentMode:PHImageContentModeAspectFill options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info)
             {
                 if (result)
                 {
                     image = result;
                 }
             }];
        }
        
        dispatch_queue_t queue = dispatch_get_main_queue();
        dispatch_sync(queue, ^{
            
            success(image);
        });
    });
}

+ (void)downloadVideoInfoForAssets:(PHAsset *)asset videoInfo:(void (^)(NSURL *, float, double, UIImage *))infoBlock
{
    PHVideoRequestOptions *voptions = [[PHVideoRequestOptions alloc] init];
    voptions.version = PHVideoRequestOptionsVersionOriginal;
    voptions.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
    [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:voptions resultHandler:^(AVAsset * _Nullable vasset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
        if ([vasset isKindOfClass:[AVURLAsset class]])
        {
            //                NSLog(@"=====%@", [NSThread currentThread]);
            AVURLAsset *urlAsset = (AVURLAsset *)vasset;
            NSNumber *size; // 视频大小
            [urlAsset.URL getResourceValue:&size forKey:NSURLFileSizeKey error:nil];
            float fileSize = 1.0*[size integerValue] / 1024;
            NSURL *videoUrl = urlAsset.URL; // 视频路径
            CMTime   time = [urlAsset duration];
            int seconds = ceil(time.value/time.timescale); // 视频时长
            
            // 获取视频原图
            [[PHImageManager defaultManager] requestImageDataForAsset:asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
                // 得到原图
                UIImage *image = [UIImage imageWithData:imageData];
                NSLog(@"srcImage.size=%@; orientation=%ld", NSStringFromCGSize(image.size), (long)orientation);
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (infoBlock)
                    {
                        infoBlock(videoUrl, fileSize, seconds, image);
                    }
                });
            }];
            
        }
    }];
}


@end
